<?php

namespace services\models;

use Yii;
use common\models\AreaTable;
use yii\base\Exception;

/**
 * This is the model class for table "tmall1.member_address".
 *
 * @property integer $uid
 * @property integer $member_uid
 * @property integer $s1_uid
 * @property integer $s2_uid
 * @property integer $s3_uid
 * @property string $consignee
 * @property string $s1
 * @property string $s2
 * @property string $s3
 * @property string $address
 * @property string $zipcode
 * @property string $cell
 * @property string $tel1
 * @property string $tel2
 * @property string $tel3
 * @property string $order_email
 * @property integer $is_default
 * @property integer $addtime
 */
class MemberAddress extends \common\models\MemberAddress
{
    public $express_charge = 0;
    public static $_EXPRESS_CHARGE = NULL;
    public static $_EMPTY_DEFAULT_ADDRESS = '为了快递能更快更准确的给您派件，需要您重新填写的收货地址，给您造成的不便敬请谅解';
    public function rules()
    {
        $newRule = [
            // 在这里定义验证规则
            ['consignee', 'required', 'message' => '您未填写收货人！'],
            ['consignee', 'match', 'pattern' => '/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u', 'message' => '收货人名称限制为中英文'],
            ['consignee', 'string', 'min' => '1', 'max' => '10'],
            ['cell', 'match', 'pattern' => '/^1[34578]{1}\d{9}$/', 'message' => '请输入11位手机号或者固定电话号码！'],
            //['address', 'match', 'pattern' => '/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u', 'message' => '详细地址限制为中英f文加数字，请规范格式！'],
            [['zipcode'], 'integer', 'max' => 999999],
            ['s1', 'required', 'message' => '请选择收货地址!'],
            ['s2', 'required', 'message' => '请选择收货地址!'],
            ['s3', 'required', 'message' => '请选择收货地址!'],
            ['address', 'required', 'message' => '详细地址限制为中英文加数字，请规范格式！'],
            [['s1_uid', 's2_uid', 's3_uid', 'is_default', 'addtime'], 'integer'],
            [['address', 'consignee', 'cell', 's1_uid', 's2_uid', 's3_uid', 's1', 's2', 's3'], 'required'],

        ];
        $ruleParent = parent::rules();

        return array_merge($newRule, $ruleParent);
    }

    public function afterFind()
    {
        $this->chargeExpress();
        parent::afterFind();
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['null'] = [];
        return $scenarios;
    }

    //过滤字段
    public function getParams($params)
    {
        if (!is_array($params))
            return false;

        //$params['is_default'] = $params['is_default'];
        //$params['addtime'] = time();
        $params['s1_uid'] = isset($params['s1_uid']) ? $params['s1_uid'] : '';
        $params['s2_uid'] = isset($params['s2_uid']) ? $params['s2_uid'] : '';
        $params['s3_uid'] = isset($params['s3_uid']) ? $params['s3_uid'] : '';


        if (!empty($params['s1_uid'])) {
            $params['s1'] = $this->getAreaStr($params['s1_uid']);
        } else {
            unset($params['s1_uid']);
        }

        if (!empty($params['s2_uid'])) {
            $params['s2'] = $this->getAreaStr($params['s2_uid']);
        } else {
            unset($params['s2_uid']);
        }

        if (!empty($params['s3_uid'])) {
            $params['s3'] = $this->getAreaStr($params['s3_uid']);
        } else {
            unset($params['s3_uid']);
        }

        foreach ($params as $key => $val) {
            if (!in_array($key, array_keys($this->attributes))) {
                unset($params[$key]);
                continue;
            }
            $this->$key = $params[$key];
        }

        $this->load($params);

        if (!$this->validate()) {
            return false;
        }

        return $this->$key;
    }

    //获取当前用的地址列表
    public function addressList($member_uid)
    {
        $member_uid = intval($member_uid);

        if (empty($member_uid))
            return false;

        return $this->find()->where('member_uid= :member_uid', [':member_uid' => $member_uid])->orderBy(['is_default' => SORT_DESC, 'addtime' => SORT_DESC])->all();

    }

    //设置默认地址
    public function addressSetDefault($member_uid, $uid = '')
    {
        $uid = intval($uid);
        $member_uid = intval($member_uid);
        if (empty($member_uid))
            return false;

        //查询当前用户是否有默认
        $resultData = $this->find()->andWhere(['member_uid' => $member_uid, 'is_default' => 1])->count();
        if ($resultData > 0) {
            $this->updateAll(['is_default' => 0], ['member_uid' => $member_uid, 'is_default' => 1]);
        }

        //如果有地址的uid 是指默认
        if (!empty($uid)) {

            $address = $this->findOne($uid);
            $address->is_default = 1;
            if (1 != $address->save()) {
                return false;
            }
        }
        return true;

    }


    //添加地址
    public function addressSetAdd($params)
    {
        //过滤赋值
        if (!is_array($params))
            return ['data' => '', 'msg' => '参数错误！', 'code' => '-402'];

        if (empty($params['member_uid'])) {
            return ['data' => '', 'msg' => '参数错误！', 'code' => '-403'];
        }

        if (isset($params['is_default']) && $params['is_default'] == 1)
            $this->addressSetDefault($params['member_uid']);//取消当前用户默认

        $this->getParams($params);


        if ($this->validate()) {

            if ($this->save()) {
                self::chargeExpress();                  //初始化默认
                $attr = $this->attributes;
                $attr['express_charge'] =$this->express_charge;
                return ['data' => $attr, 'msg' => '添加成功！', 'code' => '200'];
            }
        }

        return ['data' => '', 'msg' => $this->getErrors(), 'code' => '-404'];
    }

    public function addressSetDel($member_uid, $uid)
    {
        $uid = intval($uid);
        $member_uid = intval($member_uid);
        if (empty($uid) || empty($member_uid))
            return ['data' => '', 'msg' => '参数错误！', 'code' => '-411'];

        $customerAddress = $this->find()->where(['uid' => $uid, 'member_uid' => $member_uid])->one();

        if ($customerAddress && $customerAddress->delete())
            return ['data' => $uid, 'msg' => '删除成功！', 'code' => '200'];
        else
            return ['data' => '', 'msg' => '删除失败！', 'code' => '-404'];
    }

    public function addressSetEdit($params)
    {
        if (!is_array($params))
            return ['data' => '', 'msg' => '参数错误！', 'code' => '-404'];
        $uid = intval($params['uid']);
        if ($uid == 0)
            return ['data' => '', 'msg' => '修改地址未找到！', 'code' => '-411'];
        $member_uid = intval($params['member_uid']);
        if (empty($uid) || empty($member_uid))
            return ['data' => '', 'msg' => '参数错误！', 'code' => '-411'];


        $modele = $this->find()->where(['uid' => $uid, 'member_uid' => $member_uid])->one();
        //验证
       
        if (isset($params['is_default']) && $params['is_default'] == 1)
            $modele->addressSetDefault($member_uid);//设置默认当前用户默认

        $modele->getParams($params);
        if ($modele->validate()) {

            if ($modele->save()) {
                //初始化运费
                $this->s1_uid = $modele->s1_uid;
                self::chargeExpress();
                $attr = $modele->attributes;
                $attr['express_charge'] =$this->express_charge;
                return ['data' => $attr, 'msg' => '修改成功！', 'code' => '200'];
            }
        }

        return ['data' => $this->attributes, 'msg' => $modele->getErrors(), 'code' => '-405'];
    }

    //取得当前用户地址信息
    public function getMemberAddressInfo($member_uid, $uid=''){

        $member_uid = intval($member_uid);
        if (empty($member_uid))
            return ['data' => '', 'msg' => '参数错误！', 'code' => '-411'];

        $whereArr = array('member_uid'=>$member_uid);

        if($uid !=''){
            $whereArr['uid'] = $uid;
        }

        $dataInfo = $this->find()->where($whereArr)->orderBy(['is_default'=>SORT_DESC,'addtime'=>SORT_DESC])->one();
        return $dataInfo;

    }

    //获取城市地址信息
    public function getAreaAddress($parent_id, $layer)
    {

        if (empty($parent_id) || empty($layer))
            return false;

        $AreaTable = new AreaTable();
        $info =$AreaTable->find()->andOnCondition(['parent_id' => $parent_id, 'layer' => $layer,'is_show'=>1]);
        //除去一级不要的城市
        return $info->all();
    }

    //获取城市名称
    //id对应响应的省市区
    public function getAreaStr($id = '')
    {
        if (!is_numeric($id))
            return false;
        //获取响应的数据
        $infoArea = AreaTable::findOne(['uid' => $id]);
        if (!is_object($infoArea))
            return false;
        return $infoArea->name;
    }


    /**
     * 取得地址的快递费用
     *
     * @param int $id 地址表的uid
     * @return mixed
     */
    public function chargeExpress()
    {
        if(static::$_EXPRESS_CHARGE == null){
            static::$_EXPRESS_CHARGE = require Yii::getAlias('@common') . '/config/express-charge.php';
            arsort(static::$_EXPRESS_CHARGE);
        }

        $this->express_charge = static::$_EXPRESS_CHARGE[$this->s1_uid];

        try {
            $this->express_charge = static::$_EXPRESS_CHARGE[$this->s1_uid];
        } catch (Exception $e) {
            $this->express_charge = static::$_EXPRESS_CHARGE[0];
        }

    }


}
